package com.zxtech.zzm.core.util

import android.os.Build
import android.util.Log
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStreamReader

object RootUtil {
  val isDeviceRooted: Boolean
    get() = checkRootMethod1() || checkRootMethod2() || checkRootMethod3()

  private fun checkRootMethod1(): Boolean {
    val buildTags = Build.TAGS
    return buildTags != null && buildTags.contains("test-keys")
  }

  private fun checkRootMethod2(): Boolean {
    val paths = arrayOf(
        "/system/app/Superuser.apk",
        "/sbin/su",
        "/system/bin/su",
        "/system/xbin/su",
        "/data/local/xbin/su",
        "/data/local/bin/su",
        "/system/sd/xbin/su",
        "/system/bin/failsafe/su",
        "/data/local/su",
        "/su/bin/su"
    )
    for (path in paths) {
      if (File(path).exists()) return true
    }
    return false
  }

  private fun checkRootMethod3(): Boolean {
    var process: Process? = null
    return try {
      process = Runtime.getRuntime()
          .exec(arrayOf("/system/xbin/which", "su"))
      val `in` = BufferedReader(InputStreamReader(process.inputStream))
      `in`.readLine() != null
    } catch (t: Throwable) {
      false
    } finally {
      process?.destroy()
    }
  }

  private val TAG = "CommonUtil"
  val isRoot: Boolean
    get() {
      val binPath = "/system/bin/su"
      val xBinPath = "/system/xbin/su"
      return if (File(binPath).exists() && isExecutable(binPath)) {
        true
      } else File(
        xBinPath
      ).exists() && isExecutable(xBinPath)
    }

  private fun isExecutable(filePath: String): Boolean {
    var p: Process? = null
    try {
      p = Runtime.getRuntime()
        .exec("ls -l $filePath")
      // 获取返回内容
      val `in` = BufferedReader(InputStreamReader(p.inputStream))
      val str = `in`.readLine()
      Log.i(TAG, str!!)
      if (str != null && str.length >= 4) {
        val flag = str[3]
        if (flag == 's' || flag == 'x') {
          return true
        }
      }
    } catch (e: IOException) {
      e.printStackTrace()
    } finally {
      p?.destroy()
    }
    return false
  }
}